import db from '../db/index.js'
import bcrypt from 'bcryptjs'

// 查询用户信息接口
export async function getUserInfo(req, res) {
  
  try {
    // 查询用户信息
    const [rows] = await db.query('SELECT * FROM user WHERE username = ?', req.user.username);

    // 如果用户不存在，返回404 Not Found错误
    if (rows.length === 0) {
      return res.status(404).json({
        status: 404,
        message: '用户不存在',
      });
    }
    // 返回用户信息
    const user = rows[0];
    const userPic = user.user_pic ? `data:image/jpeg;base64,${user.user_pic.toString('base64')}` : null;
    const data = {
      username: user.username,
      email: user.email,
      user_pic: userPic,
      nickname: user.nickname
    };
    res.status(200).json({
      status: 200,
      message: '查询成功',
      data,
    });
  } catch (err) {
    console.log('Error querying database:', err);
    res.status(500).json({
      status: 500,
      message: '服务异常',
    });
  }
}


// 更新用户信息接口
export async function updateUserInfo(req, res) {

  try {
  // 更新用户信息
  const [result] = await db.query('UPDATE user SET email = ?, nickname = ? WHERE id = ?', [req.body.email, req.body.nickname, req.user.id]);
  
  // 如果更新失败，返回500错误
  if (result.affectedRows === 0) {
    return res.status(500).json({
      status: 500,
      message: '更新失败',
    });
  }
  // 返回更新后的用户信息
  const [rows] = await db.query('SELECT * FROM user WHERE id = ?', req.user.id);
  const user = rows[0];
  const data = {
    username: user.username,
    email: user.email,
    user_pic: user.user_pic,
    nickname: user.nickname
  };
  res.status(200).json({
    status: 200,
    message: '更新成功',
    data,
  });
  } catch (err) {
  console.log('Error querying database:', err);
  res.status(500).json({
  status: 500,
  message: '服务异常',
  });
  }
  }


// 更新用户头像接口
export async function updateUserAvatar(req, res) {

  try {
  // 获取头像图片的base64编码
  const base64Image = req.body.avatar.split(',')[1];
  
  // 将base64编码转换为Buffer
  const buffer = Buffer.from(base64Image, 'base64');
  
  // 上传头像图片到数据库
  const [updateResult] = await db.query('UPDATE user SET user_pic = ? WHERE id = ?', [buffer, req.user.id]);
  
  // 如果更新失败，返回500错误
  if (updateResult.affectedRows === 0) {
    return res.status(500).json({
      status: 500,
      message: '更新失败',
    });
  }
  
  // 返回更新后的用户信息
  const [rows] = await db.query('SELECT * FROM user WHERE id = ?', req.user.id);
  
  res.status(200).json({
    status: 200,
    message: '更新成功',
    
  });
} catch (err) {
  console.log('Error querying database:', err);
  res.status(500).json({
  status: 500,
  message: '服务异常',
  });
  }
  }


// 用户头重置密码
export async function updateUserPassword(req, res) {

  const { old_pwd, new_pwd,re_pwd} = req.body;

  try {

    // 查询用户信息
    const [rows] = await db.query('SELECT * FROM user WHERE username = ?', [req.user.username]);
    const user = rows[0];

    const  isPasswordValid = bcrypt.compareSync(old_pwd,rows[0].password)//验证密码

    // 验证旧密码是否匹配
    if (!isPasswordValid) {
      return res.status(400).json({
        status: 400,
        message: '旧密码不正确',
      });
    }
    // 验证新密码和确认密码是否一致
    if (new_pwd !== re_pwd) {
      return res.status(400).json({
        status: 400,
        message: '新密码和确认密码不一致',
      });
    }
    const newPassword = bcrypt.hashSync(new_pwd, 10);
    // 更新用户密码
    await db.query('UPDATE user SET password = ? WHERE username = ?', [newPassword, user.username]);

    res.status(200).json({
      status: 200,
      message: '密码更新成功',
    });
  } catch (err) {
    console.log('Error querying database:', err);
    res.status(500).json({
      status: 500,
      message: '服务异常',
    });
  }
}